import environment from "./environments"; // 环境，服务配置文件
import { getToken, setToken, removeToken } from "@/common/utils/token";
import type { RequestMethod } from "./types";

const baseUrl = environment.envConfigs.url;

export interface requestType {
  code: number;
  data?: any;
  message: string;
  status: boolean;
}


export const request = async (
  url: string,
  method:RequestMethod,
  datas: any,
  options: any = {}
): Promise<requestType> => {
  url = baseUrl + url;
  const requestUrl = url;
  const token = await getToken();
  const authHeaders = {
    Authorization: token ? `Bearer ${token}` : "",
  };
  try {
    const res: any = await uni.request({
      url: requestUrl,
      method,
      data: datas,
      header: Object.assign(authHeaders, options?.headers),
      ...options
    });

    const { data }: any = res;

    if (res.data.code === 401) {
      //需要重新登录清除store
      removeToken();
      uni.reLaunch({
        url: "",
      });
      return Promise.reject("需要重新登录");
    }

    if (res.statusCode !== 200) {
      uni.showToast({
        icon: "none",
        title: "系统错误！",
      });
      return Promise.reject("系统错误");
    }

    // if (res.data.code === 200) {
    //   return Promise.resolve(data);
    // }
    return Promise.resolve(res);

    //异常抛出
    return Promise.reject(res.data.message);
  } catch (error) {
    return Promise.reject("请求失败");
  }
};
